<?php

declare(strict_types=1);

namespace App\Activity\Job;
use App\Order\Model\OrderModel;
use App\Activity\Service\Free\FreeBaseService;
use Hyperf\AsyncQueue\Job;
use Hyperf\Utils\ApplicationContext;

class FreeOrderJob extends Job
{
    public $params;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     *
     * @var int
     */
    protected $maxAttempts = 2;

    public function __construct($params)
    {
        $this->params = $params;
    }

    /**
     * type = 1 不许二次激活||二次激活后 type=2 允许二次激活未激活
     */
    public function handle()
    {
        $container = ApplicationContext::getContainer();
        $need_invited_num = OrderModel::query()->where(['order_no' => $this->params['order_no']])->value('need_invited_num');
        $order_num = OrderModel::query()->where(['order_source' => 1, 'order_type' => 10, 'is_pay' => 1, 'free_parent_order_no' => $this->params['order_no']])->where('refund_at', '=', null)->count('order_no');
        switch ($this->params['type']) {
            case 1:
                if ($order_num < $need_invited_num) {
                    OrderModel::where(['order_no' => $this->params['order_no']])->update(['is_freed' => 3, 'free_step' => 3]);
                }
                break;
            case 2:
                if ($order_num < $need_invited_num) {
                    OrderModel::where(['order_no' => $this->params['order_no']])->update(['is_freed' => 1, 'free_step' => 2]);
                    $container->get(FreeBaseService::class)->freeActivationCommonStatus($this->params['order_no'], $this->params['second_activation']);
                }
                break;
            case 3:
                $free_num = OrderModel::query()->where(['order_no'=>$this->params['order_no']])->value('free_num');
                if($free_num == 1){
                    OrderModel::where(['order_no' => $this->params['order_no']])->update(['is_freed' => 3, 'free_step' => 3]);
                }
                break;
            default:
                break;
        }
    }

}
